package com.example.wenmini.service;

import com.example.wenmini.entity.Proxy;
import com.example.wenmini.service.humanlike.FingerprintGenerator;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
public class DriverService {
    private static final Random random = new Random();
    private static final int DEFAULT_PAGE_LOAD_TIMEOUT = 30;
    private static final int DEFAULT_SCRIPT_TIMEOUT = 30;
    private static final int DEFAULT_IMPLICIT_WAIT = 10;

    @Value("${webdriver.chrome.binary}")
    private String chromeBinaryPath;

    @Value("${webdriver.chrome.driver}")
    private String chromeDriverPath;

    @Autowired
    private FingerprintGenerator fingerprintGenerator;

    @Autowired
    private ProxyService proxyService;


    /**
     * 创建新的WebDriver实例
     */
    public WebDriver createWebDriver(boolean useProxy) {
        try {
            log.info("开始创建WebDriver实例...");
            System.setProperty("webdriver.chrome.driver", chromeDriverPath);

            ChromeOptions options = new ChromeOptions();
            
            // 设置Chrome二进制文件路径
            if (chromeBinaryPath != null && !chromeBinaryPath.isEmpty()) {
                options.setBinary(chromeBinaryPath);
            }

            // 配置代理
            if (useProxy) {
                configureProxy(options);
            }

            // 设置无头模式
            options.addArguments("--headless=new");

            // 配置浏览器首选项
            configureBrowserPreferences(options);

            // 添加Chrome启动参数
            addChromeArguments(options);

            // 设置随机User-Agent
            options.addArguments("--user-agent=" + fingerprintGenerator.generateUserAgent());

            // 创建WebDriver实例
            WebDriver driver = new ChromeDriver(options);

            // 配置超时设置
            configureTimeouts(driver);

            // 注入动态指纹
            injectFingerprint(driver);

            log.info("WebDriver实例创建成功");
            return driver;

        } catch (Exception e) {
            log.error("创建WebDriver实例失败：{}", e.getMessage());
            throw new RuntimeException("创建WebDriver实例失败", e);
        }
    }

    /**
     * 配置代理
     */
    private void configureProxy(ChromeOptions options) {
        try {
            log.info("开始配置代理...");
            Proxy proxyInfo = proxyService.getProxy();
            if (proxyInfo != null) {
                org.openqa.selenium.Proxy seleniumProxy = new org.openqa.selenium.Proxy();
                String proxyAddress = String.format("%s:%d", proxyInfo.getIp(), proxyInfo.getPort());
                seleniumProxy.setHttpProxy(proxyAddress);
                seleniumProxy.setSslProxy(proxyAddress);
                options.setProxy(seleniumProxy);
                log.info("代理配置成功：{}", proxyAddress);
            } else {
                log.warn("未能获取到有效代理");
            }
        } catch (Exception e) {
            log.error("配置代理失败：{}", e.getMessage());
            throw new RuntimeException("配置代理失败", e);
        }
    }

    /**
     * 配置浏览器首选项
     */
    private void configureBrowserPreferences(ChromeOptions options) {
        Map<String, Object> prefs = new HashMap<>();
        prefs.put("profile.default_content_setting_values.geolocation", 1);
        prefs.put("profile.default_content_settings.geolocation", 1);
        prefs.put("credentials_enable_service", false);
        prefs.put("profile.password_manager_enabled", false);
        prefs.put("webkit.webprefs.default_font_size", 16);
        prefs.put("webkit.webprefs.default_fixed_font_size", 16);
        prefs.put("intl.accept_languages", "zh-CN,zh,en-US,en");
        
        // 禁用自动化标记
        prefs.put("webrtc.ip_handling_policy", "disable_non_proxied_udp");
        prefs.put("webrtc.multiple_routes_enabled", false);
        prefs.put("webrtc.nonproxied_udp_enabled", false);
        
        options.setExperimentalOption("prefs", prefs);
    }

    /**
     * 添加Chrome启动参数
     */
    private void addChromeArguments(ChromeOptions options) {
        options.addArguments(
                "--no-sandbox",
                "--disable-dev-shm-usage",
                "--disable-gpu",
                "--disable-extensions",
                "--disable-automation",
                "--disable-blink-features=AutomationControlled",
                "--disable-infobars",
                "--window-size=1920,1080",
                "--start-maximized",
                "--ignore-certificate-errors",
                "--disable-web-security",
                "--allow-running-insecure-content",
                "--lang=zh-CN",
                "--disable-notifications",
                "--mute-audio",
                "--disable-features=WebRtcHideLocalIpsWithMdns"
        );
    }

    /**
     * 配置超时设置
     */
    private void configureTimeouts(WebDriver driver) {
        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(DEFAULT_PAGE_LOAD_TIMEOUT));
        driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(DEFAULT_SCRIPT_TIMEOUT));
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(DEFAULT_IMPLICIT_WAIT));
    }

    /**
     * 注入指纹
     */
    private void injectFingerprint(WebDriver driver) {
        try {
            fingerprintGenerator.injectDynamicFingerprint(driver);
        } catch (Exception e) {
            log.warn("注入指纹失败：{}", e.getMessage());
        }
    }


}
